package com.example.goodpet.my.activity;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.goodpet.R;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.AppNetConfig;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.GlideCacheUtil;
import com.example.goodpet.utils.ImageUtil;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.UIUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.iceteck.silicompressorr.SiliCompressor;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MyInformationActivity extends FragmentActivity {
    private static final String TAG = "MyInformationActivity";
    private final int PICTURE=1;

    private CircleImageView portrait;
    private TextView phoneNulber;
    private EditText nickname;
    private RadioGroup sexGroup;
    private RadioButton btnMan;
    private EditText signature;
    private Button submit;
    private TextView cmTitleText;
    private ImageView cmTitleLeft;
    private TextView cmTitleRight;

    //private long newChangeDate;//时间戳
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_information);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        //newChangeDate=0;
        cmTitleText=findViewById(R.id.cmTitleText);
        cmTitleLeft=findViewById(R.id.cmTitleLeft);
        cmTitleRight=findViewById(R.id.cmTitleRight);

        phoneNulber=findViewById(R.id.tvPhoneNumber);
        portrait=findViewById(R.id.portrait);
        nickname=findViewById(R.id.tvNickname);
        sexGroup=findViewById(R.id.rpSex);
        btnMan=findViewById(R.id.btnMan);
        signature=findViewById(R.id.signature);
        submit=findViewById(R.id.btnSubmit);
        initViewContent();
        initListener();
        initTitle();
    }
    private void initTitle(){
        cmTitleText.setText("我的信息");
        cmTitleLeft.setVisibility(View.INVISIBLE);
        cmTitleRight.setVisibility(View.INVISIBLE);
    }
    private void initListener() {
        portrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(picture, PICTURE);
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Retrofit build = new Retrofit.Builder().baseUrl(AppNetConfig.BASE_URL).build();
                UserService userService = build.create(UserService.class);
                int gender=btnMan.isChecked()?0:1;
                String nicknameStr=nickname.getText().toString();
                String signatureStr=signature.getText().toString();
                userService.updateUserInformation(MyApplication.user.getId(),gender,nicknameStr,signatureStr).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String string = response.body().string();
                            JsonObject jsonObject = JsonParser.parseString(string).getAsJsonObject();
                            boolean success = jsonObject.get("success").getAsBoolean();
                            if (success){
                                MyApplication.user.setNickname(nicknameStr);
                                MyApplication.user.setGender(gender);
                                MyApplication.user.setSignature(signatureStr);
                                MyApplication.updateMyUserInfo(nicknameStr,signatureStr,gender);
                                //System.out.println(MyApplication.user.toString());
                                SharedPreferences.Editor editor = getSharedPreferences("userInfo", MODE_PRIVATE).edit();
                                editor.putInt("gender",gender);
                                editor.putString("nickname",nicknameStr);
                                editor.putString("signature",signatureStr);
                                editor.apply();
                                //System.out.println(MyApplication.user);
                                UIUtils.toast("修改成功！",false);
                                finish();
                            }else {
                                UIUtils.toast("修改失败！",false);
                                finish();
                            }
                        } catch (IOException e) {

                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        UIUtils.toast("联网失败！",false);
                    }
                });
            }
        });
    }

    @SuppressLint("CheckResult")
    private void initViewContent() {
        //System.out.println(MyApplication.user.getPortrait());
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.circleCrop()
                .skipMemoryCache(true)
                .diskCacheStrategy( DiskCacheStrategy.NONE );
        Glide.with(this).load(Constants.BASE_URL_IMAGE+MyApplication.user.getPortrait()).apply(requestOptions)./*signature(new ObjectKey(newChangeDate)).*/into(portrait);
        phoneNulber.setText(MyApplication.user.getPhoneNumber());
        nickname.setText(MyApplication.user.getNickname());
        signature.setText(MyApplication.user.getSignature());
        sexGroup.check(MyApplication.user.getGender()==0?R.id.btnMan:R.id.btnWoman);
    }


//调取系统相册的结果
    @SuppressLint("ResourceType")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        GlideCacheUtil.getInstance().clearImageAllCache(UIUtils.getContext());
        if (requestCode == PICTURE && resultCode == RESULT_OK && data != null) {
            Uri picture = data.getData();
            Bitmap bitmap;
            try {
                bitmap=SiliCompressor.with(this).getCompressBitmap(String.valueOf(picture));
                        portrait.setImageBitmap(bitmap);
                //bitmap = BitmapFactory.decodeFileDescriptor(getContentResolver().openFileDescriptor(picture, "r").getFileDescriptor());
                portrait.setImageBitmap(bitmap);
                //更新时间戳
                //newChangeDate=System.currentTimeMillis();

                String imgStr = ImageUtil.ImageToString(bitmap);
                Retrofit build = new Retrofit.Builder().baseUrl(AppNetConfig.BASE_URL).build();
                UserService userService = build.create(UserService.class);
                userService.portraitChange(imgStr,MyApplication.user.getId()).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String string = response.body().string();
                            Log.d(TAG, "onResponse: "+string);
                            JsonObject jsonObject = JsonParser.parseString(string).getAsJsonObject();
                            boolean success = jsonObject.get("success").getAsBoolean();
                            if (success){
                                String portraitUrl = jsonObject.get("portraitUrl").getAsString();
                                MyApplication.user.setPortrait(portraitUrl);
                                MyApplication.updateMyUserPortrait(portraitUrl);
                                //加载头像
                                RequestOptions requestOptions = new RequestOptions();
                                requestOptions.circleCrop()
                                        .skipMemoryCache(true)
                                        .diskCacheStrategy( DiskCacheStrategy.NONE );
                                Glide.with(MyInformationActivity.this).load(Constants.BASE_URL_IMAGE+MyApplication.user.getPortrait()).apply(requestOptions)./*signature(new ObjectKey(newChangeDate)).*/into(portrait);
                                //加载结束
                                SharedPreferences.Editor userInfo = getSharedPreferences("userInfo", MODE_PRIVATE).edit();
                                userInfo.putString("portrait",portraitUrl).apply();
                                UIUtils.toast("上传成功！",false);
                            }else {
                                UIUtils.toast("上传失败！",false);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        UIUtils.toast("网络连接失败",false);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}